﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NodeEditer;
using UnityEditor;
using UnityEngine;
using LitJson;
using System.IO;
namespace BehaviorSystem
{
    public class BehaviourNodeEditorWindow : EditorNodeWindowBase
    {


        //[SerializeField]
        //public Texture2D NewNodeTex;

        int gridSize = 40;

        bool isRefresh;

        Vector2 gridOffset ;

        Vector2 contextSize = new Vector2(100, 300);

        NodeData curNodeData;

        BehaviourEditorNodeDrawer nodeDrawer = new BehaviourEditorNodeDrawer();

        NodeTempleteEditorWindow nodeTempleteEditWindow = new NodeTempleteEditorWindow();


        static int index;

        protected static EditorWindow window;


        [MenuItem("CustomTools/Behavior/BehaviourNodeEditor")]
        static void OpenWindow()
        {
            window = EditorWindow.GetWindow<BehaviourNodeEditorWindow>();
            window.maximized = true;

        }

        private void OnEnable()
        {
            nodeDrawer.NodeEditorWindow = this;

            string json = File.ReadAllText(Application.dataPath + "/Resources/NodeDatas/TestTree.json");

            JsonData jsonData =  JsonMapper.ToObject(json);

            curNodeData = new NodeData();
            curNodeData.DeSerialize(jsonData["Tree"]);

            ResolveLayout();
        }

        public override void ResolveLayout()
        {
            DownRect = new Rect(0, this.position.height * 19 / 20, this.position.width, this.position.height * 1 / 20);
            ToolBarRect = new Rect(0, this.position.height * 1 / 20, this.position.width, this.position.height * 1 / 20);
            
            LeftRect = new Rect(0, ToolBarRect.height, this.position.width / 5, this.position.height - ToolBarRect.height - DownRect.height);
            RightRect = new Rect(LeftRect.x + LeftRect.width, LeftRect.y, this.position.width - LeftRect.width, this.position.height - ToolBarRect.height - DownRect.height);
            
        }
        public override void DrawToolBar()
        {
            GUILayout.BeginHorizontal();
            if (GUILayout.Button("NodeTempleteWindow"))
            {
                nodeTempleteEditWindow.IsOpen = true;
            }
            nodeTempleteEditWindow.DrawEditorWindow();
            GUILayout.EndHorizontal();

        }

        public override void DrawLeft()
        {
           
        }

        public override void DrawRight()
        {

            DrawGrid();
            GUILayout.BeginArea(RightRect);
            DrawNodes();
            if (isFirst)
            {
                isFirst = false;
                Repaint();
            }
            DrawContexxt();



            GUILayout.EndArea();


        }

        void DrawGrid()
        {

            Color dCol = Handles.color;
            Color gridColor = Color.green;
            //GUI.DrawTexture(canvas, gridTex, ScaleMode.StretchToFill);

            int wlines = Mathf.RoundToInt(RightRect.width / gridSize);
            int hlines = Mathf.RoundToInt(RightRect.height / gridSize);
            
            Handles.color = Color.blue; 
            for (int i = 0; i < wlines; i++)
            {
                Handles.DrawLine(new Vector3(gridOffset.x + RightRect.x + i * gridSize, gridOffset.y + RightRect.y, 0), new Vector3(gridOffset.x + RightRect.x + i * gridSize, gridOffset.y + RightRect.y + RightRect.height, 0));
                
            } 
            Handles.color = Color.green;

            for (int i = 0; i < hlines; i++)
            {
                Handles.DrawLine(new Vector3(gridOffset.x + RightRect.x, gridOffset.y + RightRect.y + i * gridSize, 0), new Vector3(gridOffset.x + RightRect.x + RightRect.width, gridOffset.y + RightRect.y + i * gridSize, 0));

            } 
            Handles.color = dCol;
          
        }

        public override void DrawNodes()
        {
            BeginWindows();
            if (NodeId2NodeDataRects.ContainsKey(curNodeData.Id))
            {
                nodeDrawer.ComputeNodeNeedWidth(curNodeData, NodeId2NodeDataRects[curNodeData.Id].WindowRect.width);
                nodeDrawer.DrawNode(curNodeData, NodeId2NodeDataRects[curNodeData.Id].WindowRect);
            }
            else
            {
                nodeDrawer.ComputeNodeNeedWidth(curNodeData, nodeDrawer.windowRect.width);
                nodeDrawer.InitLayout();
                nodeDrawer.DrawNode(curNodeData, nodeDrawer.windowRect);
            }
            EndWindows();
        }
        bool a = true;
        /// <summary>
        /// 绘制菜单
        /// </summary>
        public void DrawContexxt()
        {


                Rect contextRect = new Rect(ContextClickPos, contextSize);
                GUILayout.BeginArea(contextRect, EditorStyles.helpBox);
                DrawContexxtButton("向前添加节点", null);
                DrawContexxtButton("向后添加节点", null);
                DrawContexxtButton("添加子节点", AddChildNode);
                DrawContexxtButton("删除节点", DeleteNode);

                GUILayout.EndArea();



            if (a)
            {
  
            }



        }

        private void DrawContexxtButton(string btnName,Action OnButtonClick)
        {
            if (GUILayout.Button(btnName)) {
                if (OnButtonClick != null)
                {
                    OnButtonClick.Invoke();
                }
                ContextClickPos = ContextClickPosOffset;
            }
        }

        #region 节点数据操作

        private void AddChildNode()
        {
            NodeData nodeData = new NodeData();
            nodeData.Id = NodeId2NodeDataRects.Count+1;
            nodeData.ChildNodes = new List<NodeData>();
            NodeData curSelectedNodeData = GetNodeByNodeId(curNodeData,CurSelectedNodeId);
            Debug.Log(CurSelectedNodeId);
            Debug.Log( curSelectedNodeData.Id + "        " );
            curSelectedNodeData.ChildNodes.Add(nodeData);
        }

        private void DeleteNode()
        {
            NodeData parentNodeData = GetParentNodeByChildNodeId(curNodeData, CurSelectedNodeId);

            for (int i = 0; i < parentNodeData.ChildNodes.Count; i++)
            {
                if (parentNodeData.ChildNodes[i].Id == CurSelectedNodeId) 
                {
                    parentNodeData.ChildNodes.RemoveAt(i);
                    NodeId2NodeDataRects.Remove(CurSelectedNodeId);
                }
            }
        }

        private NodeData GetNodeByNodeId(NodeData node, int foundNodeId)
        {
            if (node.Id==foundNodeId)
            {
                return node;
            }

            for (int i = 0; i < node.ChildNodes.Count; i++)
            {
                if (node.ChildNodes[i].Id == foundNodeId)
                {
                    return node.ChildNodes[i];
                }
                else
                {
                    if (node.ChildNodes[i].ChildNodes.Count > 0)
                    {
                        NodeData temp= GetNodeByNodeId(node.ChildNodes[i], foundNodeId);
                        if (temp!=null)
                        {
                            return temp;
                        }
                    }
                }
            }
            return null;
        }

        private NodeData GetParentNodeByChildNodeId(NodeData node, int foundNodeId)
        {
            for (int i = 0; i < node.ChildNodes.Count; i++)
            {
                if (node.ChildNodes[i].Id== foundNodeId)
                {
                    return node;
                }
                else
                {
                    if (node.ChildNodes[i].ChildNodes.Count>0)
                    {
                       return GetParentNodeByChildNodeId(node.ChildNodes[i], foundNodeId);
                    }
                }
            }
            return null;
        }
        #endregion
    }
}
